import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

/**
 * Created with IntelliJ IDEA.
 * User: ttq
 * Date: 13-7-5
 * Time: 下午3:17
 * To change this template use File | Settings | File Templates.
 */
public class GzipOutputStream extends ServletOutputStream {
    private HttpServletResponse response;
    private GZIPOutputStream gzipOutputStream;

    private ByteArrayOutputStream byteArrayOutputStream;

    public GzipOutputStream(HttpServletResponse response) throws IOException {
        this.response = response;
        byteArrayOutputStream = new ByteArrayOutputStream();
        gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
    }

    public void write(int b) throws IOException {
        gzipOutputStream.write(b);
    }

    public void close() throws IOException {
        gzipOutputStream.finish();
        byte[] content = byteArrayOutputStream.toByteArray();
        response.addHeader("Content-Encoding", "gzip");
        response.addHeader("Content-Length", Integer.toString(content.length));

        ServletOutputStream servletOutputStream = response.getOutputStream();
        servletOutputStream.write(content);
        servletOutputStream.close();
    }

    public void flush() throws IOException {
        gzipOutputStream.flush();
    }

    public void write(byte[] bytes, int off, int len) throws IOException {
        gzipOutputStream.write(bytes, off, len);
    }

    public void write(byte[] bytes) throws IOException {
        gzipOutputStream.write(bytes);
    }
}
